package org.example.reactor;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 单线程Reactor模式
 * 轮询IO事件和handler处理器处于同一个线程
 */
public class EchoServer {
    public static void main(String[] args) throws Exception{
        // 反应器线程
        new Thread(new EchoServerReactor()).start();
    }

    /**
     * 服务端反应器
     */
    public static class EchoServerReactor implements Runnable {

        private Selector selector;

        private ServerSocketChannel server;

        public EchoServerReactor() {
            try {
                selector = Selector.open();

                server = ServerSocketChannel.open();

                server.configureBlocking(false);

                server.bind(new InetSocketAddress("localhost", 8081));

                SelectionKey selectionKey = server.register(selector, SelectionKey.OP_ACCEPT);

                selectionKey.attach(new AcceptHandler(server, selector));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                while (!Thread.interrupted()) {
                    while (selector.select() > 0) {
                        Set<SelectionKey> selected = selector.selectedKeys();
                        Iterator<SelectionKey> iterator = selected.iterator();

                        while (iterator.hasNext()) {
                            SelectionKey skey = iterator.next();
                            try {
                                Runnable runa = (Runnable) skey.attachment();
                                runa.run();
                            } catch (Exception e) {
                                // 暂时不处理
                            }
                            iterator.remove();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
